﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using Dapper.Contrib.Extensions;
using Npgsql;

namespace DapperDemo
{
    public class DBHelper
    {
        public static ConnectionStringSettings sqlConnection = ConfigurationManager.ConnectionStrings["manager"];
        //public static Func<DbConnection> ConnectionFactory = () => new SqlConnection(connection);

        public static NpgsqlConnection OpenConnection()
        {
            //sqlConnection = ConfigurationManager.AppSettings["manager"];
            NpgsqlConnection connection = new NpgsqlConnection(sqlConnection.ConnectionString);
            connection.Open();
            return connection;
        }
    }

    public class Option
    {
        public static void TestMethod()
        {
            using (var conn = DBHelper.OpenConnection())
            {
                List<People> p = conn.Query<People>("SELECT * FROM people").ToList();
            }
        }

        public static void insert()
        {
            try
            {
                using (var conn = DBHelper.OpenConnection())
                {
                    People p = new People();
                    p.age = "123";
                    p.username = "lalla";
                    p.history = "{\"username\":1234}";
                    conn.Insert(p);
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        public static void update()
        {
            using (var conn = DBHelper.OpenConnection())
            {
                People p = new People();
                p.username = "Insert";
                p.age = "30";
                var result = conn.Update(p);
                
            }


        }

        public static string GenerateStringID(char prefix)
        {
            long i = 1;
            foreach (byte b in Guid.NewGuid().ToByteArray())
            {
                i *= ((int)b + 1);
            }
            string result = string.Format("{0:x}", i - DateTime.Now.Ticks);
            while (result.Length < 16)
            {
                Random rd = new Random();
                int number = rd.Next(97, 123);
                result += Convert.ToChar(number);
            }
            return prefix + result;
        }
    }
}
